#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time    : 2021/3/1 10:29
# @Author  : zhaohexin
# @Email   : 1483643520@xxx.com
# @File    : __init__.py.py
# @Software: PyCharm
# @FileDescription： 启动类


from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from core.config import settings
from common.Exception import NormalException
from routers.routers_v1 import routers_v1


def create_app() -> FastAPI:
    """
    创建app
    :return:
    """
    app = FastAPI(
        debug=settings.DEBUG,
        title=settings.TITLE,
        description=settings.DESCRIPTION,
        docs_url=settings.DOCS_URL,
        openapi_url=settings.OPENAPI_URL,
        redoc_url=settings.REDOC_URL
    )

    # 跨域设置
    register_cors(app)
    # 注册路由
    register_router(app)
    # 注册捕获全局异常
    register_exception(app)
    # 请求拦截
    register_hook(app)
    # 初始化链接

    return app


def register_router(app: FastAPI):
    """
    注册路由
    :param app:
    :return:
    """
    app.include_router(routers_v1)


def register_cors(app: FastAPI):
    """
    注册跨域
    :param app:
    :return:
    """
    pass


def register_exception(app: FastAPI):
    """
    全局异常捕获
    :param app:
    :return:
    """

    @app.exception_handler(NormalException)
    async def unicorn_exception_handler(request: Request, exc: NormalException):
        return JSONResponse(
            status_code=exc.status,
            content={
                "message": exc.message,
                "status": exc.status,
                "timestamp": exc.timestamp
            }
        )


def register_hook(app: FastAPI):
    """
    请求相应拦截
    :param app:
    :return:
    """
    pass
